<?php

class SearchLeftMenuWidget extends CWidget
{

    public $items;
    public $selectIds;
    public $searchIds;
    public $counts;

    private $_html = '';

    public function init()
    {
        $oCategories = new Categories();

//        $oCategoryProperty = new CategoryProperty();
//	    $this->items = $oCategoryProperty->getByType($this->selectIds, 2);

//	    print_r($this->items); exit;


//	    $items = $oCategories->getUsedCategories($ids);
//        $this->items = $oCategories->onlyPublic()->id($ids)->findAll();
//        $ids = $oCategories->getAllChild($this->selectIds);
//        $this->items = $oCategories->onlyPublic()->id($ids)->findAll();
        $this->items = $oCategories->onlyPublic()->id($this->searchIds)->findAll();

//	    foreach($this->items as $i => $arr)
//		    $this->items[$i]['childNodes'] = $items;

//        print_r($this->items); exit;
    }

    public function run()
    {
        $this->_tree($this->items);
    }

    protected function _tree($items, $level = 1, $propertyId = null, $valueId = null)
    {
	    if(!$items)
		    return $this->_html = '';

        $url = (!empty($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '');
        $url = preg_replace('`&?c=[a-z0-9_-]+`i', '', $url);
        $url = preg_replace('`&?page=\d+`i', '', $url);
        $url = '?'.($url ? $url.'&' : '');

        $this->_html .= '<ul class="'. ($level == 1 ? ' categories' : '') .'">';

        foreach($items as $i => $oRow)
        {
	        $this->_html .= '<li'. (isset($oRow->id) && isset($this->selectIds[$oRow->id]) ? ' class="selected"' : '') .'>';

	        if(!empty($oRow->type))
                $this->_html .= '<a href="'. trim($url. (!empty($_GET['c']) && $_GET['c'] == $oRow->alias ? '' : 'c='.$oRow->alias), '&') .'">'. $oRow->title . ('<i>('. (!empty($this->counts[$oRow->id]) ? $this->counts[$oRow->id] : '0') .')</i>') .'</a>';
	        else
                $this->_html .= '<div>'. $oRow['value'] .'</div>';

            $this->_html .= '</li>';
        }

        $this->_html .= '</ul>';

        return $this->_html;
    }

    public function __toString()
    {
        $this->_html = '<div class="title">Найдено в категориях</div>' . $this->_html;

//	    var_dump($this->_html);

	    if($this->_html)
		    $this->_html = '<div id="left-menu">'. $this->_html .'</div>';

        return $this->_html;
    }


}